const Promise = require('bluebird');

/**
 * @api {get} /api/admin/v1/dicts/browse 字典列表
 * @apiGroup AdminDicts
 * @apiDescription 字典管理-字典列表
 * @apiPermission 管理员(查看字典权限)
 * @apiVersion 1.0.0
 */
exports.browse = function ({query}, {models: {Dicts}, controller}) {
    return Dicts.findAndCountAll(controller.pagination({
        params: query,
        filters: ['type'],
        likes: ['value', 'text']
    }));
}

/**
 * @api {post} /api/admin/v1/dicts/add 字典添加
 * @apiGroup AdminDicts
 * @apiDescription 字典管理-字典添加
 * @apiPermission 管理员(添加字典权限)
 * @apiVersion 1.0.0
 */
exports.add = function ({body}, {models: {Dicts}, redis}) {
    return Dicts.create(body).then(function (dict) {
        /**
         * 推送字典更新消息
         */
        redis.pub.publish('dicts_update', 'dicts_update');
        return {success: true, data: dict};
    });
};

/**
 * @api {post} /api/admin/v1/dicts/edit 字典编辑
 * @apiGroup AdminDicts
 * @apiDescription 字典管理-字典编辑
 * @apiPermission 管理员(编辑字典权限)
 * @apiVersion 1.0.0
 */
exports.edit = function ({body}, {models: {Dicts}, redis}) {
    let {id} = body;
    delete body.id;
    return Dicts.update(body, {where: {id: id}}).then(function (result) {
        if (!result[0]) {
            return {success: false};
        }
        /**
         * 推送字典更新消息
         */
        redis.pub.publish('dicts_update', 'dicts_update');
        return Dicts.findOne({where: {id: id}}).then(function (dict) {
            return {success: true, data: dict};
        });
    });
};

/**
 * @api {post} /api/admin/v1/dicts/delete 字典删除
 * @apiGroup AdminDicts
 * @apiDescription 字典管理-字典删除
 * @apiPermission 管理员(删除字典权限)
 * @apiVersion 1.0.0
 */
exports.delete = function ({body}, {models: {Dicts}, redis}) {
    let {id} = body;
    return Dicts.destroy({where: {id: id}}).then(function (count) {
        if (!count) {
            return {success: false};
        }
        /**
         * 推送字典更新消息
         */
        redis.pub.publish('dicts_update', 'dicts_update');
        return {success: true};
    });
};

/**
 * @api {post} /api/admin/v1/dicts/sort 字典排序
 * @apiGroup AdminDicts
 * @apiDescription 字典管理-字典排序
 * @apiPermission 管理员(编辑字典权限)
 * @apiVersion 1.0.0
 */
exports.sort = function ({body}, {models: {Dicts}, redis}) {
    let all = [];
    for (let i in body) {
        let row = body[i];
        all.push(Dicts.update({order_by: row.order_by}, {where: {id: row.id}}));
    }
    return Promise.all(all).then(function () {
        /**
         * 推送字典更新消息
         */
        redis.pub.publish('dicts_update', 'dicts_update');
        return {success: true};
    });
};